const isNotBlank = (value) => {
  if (value && typeof (value) === 'string') {
    value = value.trim()
    if (value === '') {
      value = false
    }
  }
  return !!value
}

/** 大于等于0的整数 */
export const nonnegativeInt = (rule, value, callback) => {
  if (isNotBlank(value)) {
    const isInt = /^(0|[1-9][0-9]*)$/.test(value.toString().trim())
    if (!isInt) {
      return callback(new Error('大于等于0的整数'))
    }
  }
  return callback()
}

/** 正整数 */
export const positiveInt = (rule, value, callback) => {
  if (isNotBlank(value)) {
    const isInt = /^[1-9][0-9]*$/.test(value.toString().trim())
    if (!isInt) {
      return callback(new Error('正整数'))
    }
  }
  return callback()
}

/**
 * 两个正整数之间
 *  { validator: betweenInt(10, 30), trigger: 'blur', message:'??'}
 * @param {*} min
 * @param {*} max
 */
export const betweenInt = (min, max) => (rule, value, callback) => {
  // console.log(rule.message)
  if (isNotBlank(value)) {
    const isInt = /^[1-9][0-9]*$/.test(value.toString().trim())
    if (!isInt) {
      return callback(new Error(`${min}到${max}的正整数`))
    }
    const isBetween = value >= min && value <= max
    if (!isBetween) {
      return callback(new Error(`${min}到${max}的正整数`))
    }
  }
  return callback()
}

export const maxValue = (max) => (rule, value, callback) => {
  // console.log(rule.message)
  if (isNotBlank(value)) {
    value = Number(value)

    if (isNaN(value)) {
      return callback(new Error(`不是有效数字`))
    }
    if (value > max) {
      return callback(new Error(`不能大于${max}`))
    }
  }
  return callback()
}

export const minValue = (min) => (rule, value, callback) => {
  // console.log(rule.message)
  if (isNotBlank(value)) {
    value = Number(value)
    if (isNaN(value)) {
      return callback(new Error(`不是有效数字`))
    }
    if (value < min) {
      return callback(new Error(`不能小于${min}}`))
    }
  }
  return callback()
}

/**
 * 0以上的数值，scale位小数数，例如是scale=2 ,3 3.0  3.00 者是合法的
 * @param {*} scale
 */
export const nonnegativeDecimal = (scale) => (rule, value, callback) => {
  if (isNotBlank(value)) {
    const reg = new RegExp('^[1-9]\\d*\\.\\d{1,' + scale + '}$|^0.\\d{1,' + scale + '}$|^[1-9][0-9]*$|0$')
    if (!reg.test(value.toString().trim())) {
      return callback(new Error(`大于等于0的${scale}位小数`))
    }
  }
  return callback()
}
